package com.xywl.escort.view.pay.project

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BandCardListResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.ToastUtil
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_subscribe_order_pay_dialog.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.math.BigDecimal
import javax.inject.Inject

/**
 * 认购详情支付弹窗界面
 */
@Route(path = "/xy/subscribe/order/pay/dialog")
class SubscribeOrderPayDialogActivity : BaseActivity(), SubscribeOrderPayDialogContract.View {
    @Autowired
    @JvmField
    var couponId = ""

    @Autowired
    @JvmField
    var recordId = ""

    @Autowired
    @JvmField
    var type = 1

    @Autowired
    @JvmField
    var bandCardId = ""

    // 优惠券金额
    @Autowired
    @JvmField
    var couponPayMoney = BigDecimal("0")

    // 使用账户支付金额
    @Autowired
    @JvmField
    var accountPayMoney = BigDecimal("0")

    // 使用银行卡支付
    @Autowired
    @JvmField
    var thirdAccountPayPrice = BigDecimal("0")

    private var bandBean: BandCardListResp.DataBean.ListBean? = null

    @Inject
    lateinit var mPresenter: SubscribeOrderPayDialogContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_subscribe_order_pay_dialog)
        ARouter.getInstance().inject(this)

        initView()
        addListener()
        EventBus.getDefault().register(this)
    }

    private fun initView() {
        Timber.e("thirdAccountPayPrice=$thirdAccountPayPrice")
        Timber.e("couponPayMoney=$couponPayMoney")
        Timber.e("accountPayMoney=$accountPayMoney")
        Timber.e("bandCardId=$bandCardId")
        Timber.e("type=$type")
        Timber.e("couponId=$couponId")
        if (!TextUtils.isEmpty(couponId)) {
            layout_coupon.visibility = View.VISIBLE
        } else {
            layout_coupon.visibility = View.GONE
        }
        val balance = "抵扣账户余额(${NumberFormatUtils.getInstance().format(accountPayMoney.toDouble())})"
        text_account_balance.text = balance
        val strPayMoney = "￥:" + NumberFormatUtils.getInstance().format(thirdAccountPayPrice.toDouble())
        text_pay_price.text = strPayMoney
    }

    private fun addListener() {
        btn_confirm.setOnClickListener {
            submit()
        }

        image_close.setOnClickListener {
            finish()
        }

        text_add_band_card.setOnClickListener {
            val userId = RxSPTool.getString(this, PreferenceKeys.USER_ID)
            mPresenter.isSetPayPwd(userId)
        }

        text_coupon.setOnClickListener {
            ARouter.getInstance().build("/xy/coupon/detail")
                    .withString("couponId", couponId)
                    .withInt("type", 2)
                    .navigation()
        }
    }

    private fun submit() {
        // 是否需要输入密码： 1 - 不需要输入支付密码 【不使用账户余额支付】 2 - 需要输入支付密码 【使用账户余额支付】
        if (type == 1) {
            mPresenter.payApply(recordId)
        } else {
            ARouter.getInstance().build("/xy/verify/pay/pwd")
                    .withInt("type", 2)
                    .withString("recordId", recordId)
                    .navigation()
        }
    }

    override fun onResume() {
        super.onResume()
        mPresenter.takeView(this)
        mPresenter.getBandCardList("DC", 1, 1)
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun getBandCardListSuccess(dataBean: BandCardListResp.DataBean?) {
        val list = dataBean!!.list
        if (list.size > 0) {
            bandBean = list[0]
            val item = list[0]
            var bankName = item.bankName
            val bankCardNo = item.bankCardNo
            if (bankCardNo.length > 4) {
                bankName += " (" + bankCardNo.substring(bankCardNo.length - 4, bankCardNo.length) + ")"
            } else {
                bankName += " ($bankCardNo)"
            }
            text_add_band_card.visibility = View.GONE
            text_band_card.visibility = View.VISIBLE
            text_band_card.text = bankName
        } else {
            text_add_band_card.visibility = View.VISIBLE
            text_band_card.visibility = View.GONE
        }
    }

    override fun getBandCardListFailure() {
        Timber.e("getBandCardListFailure")
        text_add_band_card.visibility = View.VISIBLE
        text_band_card.visibility = View.GONE
    }

    override fun payApplySuccess(data: String?) {
        // 认购第二步-支付申请成功
        // data=1时，表示不使用银行卡支付，此时支付完成，不需要再调用【支付确认】接口； 当data=2时，表示需要使用银行卡支付，支付未完成，此时需要调用【支付确认】接口
        if (data.equals("1")) {
            ARouter.getInstance()
                    .build("/xy/order/subscribe/detail")
                    .withString("id", recordId)
                    .navigation()
        } else {
            // 调用确认支付界面
            ARouter.getInstance()
                    .build("/xy/pay/confirm")
                    .withString("id", recordId)
                    .navigation()
        }
    }

    override fun payApplyFailure(msg: String?) {
        // 认购第二步-支付申请失败
        ToastUtil.showTip(this, msg)
    }

    override fun hasSetPayPwd() {
        ARouter.getInstance().build("/xy/verify/pay/pwd")
                .withString("path", "/xy/band/card/bind")
                .navigation()
    }

    override fun noSetPayPwd() {
        ARouter.getInstance().build("/xy/pwd/setting/pay").navigation()
    }

    override fun findIsFitPayPwdFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("SubscribeOrderPayDialogActivity").e("event.message=" + event.message)
        Timber.tag("SubscribeOrderPayDialogActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_PAY_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.PAY_SUCCESS) {
                        finish()
                    } else if (message == Constant.EventMessage.PAY_BALANCE_SUCCESS) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
